package pers.zxk.jlytnews.base;

import pers.zxk.jlytnews.util.Constants;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public abstract class BaseServlet extends HttpServlet {
    /*//保存图片文件并返回图片的url地址
    protected String saveImage(Part part) throws IOException {
        //将图片保存到服务器image路径下
        //String filePath = getServletContext().getRealPath(Constants.UPLOADS_IMAGE_FOLDER);//获得项目的根目录,并设计文件保存路径
        Map<String, String> map = System.getenv();
        String filePath = map.get("CATALINA_HOME");
        //判断文件夹是否存在
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }

        //使用文件的MD5值作为文件名
        //这段代码有错误，明天调试
        *//*InputStream inputStream = part.getInputStream();
        String fileName = DigestUtils.md5Hex(inputStream);*//*

        // 先使用日期作为保存文件的名称fileName
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmss");
        String fileName = dateFormat.format(new Date()) + ".jpg";

        // 将文件保存到项目下的uploads文件夹下
        part.write(filePath + fileName);

        String url = Constants.BASE_URL + Constants.UPLOADS_IMAGE_FOLDER + fileName;
        return url;
    }

    //获取url对应的文件路径
    protected String urlToRealPath(String url) {
        int i = url.indexOf(Constants.UPLOADS_IMAGE_FOLDER);
        String substring = url.substring(i);
        //String replace = substring.replace("/", "\\");
        String filePath = getServletContext().getRealPath("/");//获得项目的根目录,并设计文件保存路径
        //String realPath = filePath + replace;
        String realPath = filePath + substring;
        return realPath;
    }*/
}
